/**
 * 111 处理数据拍成需要的顺序
 * 222 循环数据 制作成dom
 */

/* e.g.
<div class="box">
    <div class="item">01</div>
    <div class="item">02</div>
    <div class="item">03</div>
    <div class="item">04</div>
    <div class="item">05</div>
    <div class="item">06</div>
    <div class="item">07</div>
    <div class="item">08</div>
    <div class="item">09</div>
    <div class="item">10</div>
</div>
<script>
    // 不写高度的话默认就是黄金比例
    let buju = new Layout({
        father: '.box',
        son: '.item',
        sonWidth: 200,
        gap: 10
    })
</script>
<style>
    .box{
        background: #232323;
    }
    .item{
        background: #ccc;
    }
</style>
*/
class Layout {
  constructor(options) {
    this.options = options;

    this.init();

    try {
      window.onresize = () => {
        this.init();
      };
    } catch (error) {
      console.log("window.onresize--->", error);
    }
  }
  init() {
    this.father = document.querySelector(this.options.father);
    if (!this.father) {
      return;
    }
    this.sons = document.querySelectorAll(this.options.son);
    this.sonWidth = this.options.sonWidth || 120; // 子元素宽度
    this.sonHeight = this.options.sonHeight || 0; // 子元素高度
    this.gap = this.options.gap || 10; // 子元素之间的间隙
    this.type = this.options.type || "w>h"; // 宽高比

    let fatherWidth = Math.min(
      this.father.clientWidth,
      document.body.clientWidth
    );

    let sonWidth = this.sonWidth;
    let gap = this.gap;
    let count = Math.floor(fatherWidth / (sonWidth + gap)) || 1; // 最小要是1

    let w = (fatherWidth - (count - 1) * gap) / count;
    let h = 0;
    // 宽高比
    if (this.type == "w>h") {
      h = w / 1.618; // 黄金比例
    } else {
      h = w * 1.618; // 黄金比例
    }

    for (let i = 0; i < this.sons.length; i++) {
      let item = this.sons[i];
      // item.style.width = w + 'px'
      item.style.minWidth = w + "px";
      item.style.height = (this.sonHeight || h || 40) + "px";
    }
    this.father.style = `
        display: grid;
        grid-template-columns: repeat(${count}, 1fr);
        gap: ${gap}px;
        `;
  }
}

export default Layout;
